<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property-read SysUser|null $user
 *
 * @property string $user_account
 * @property string|null $user_password
 */
class LoginForm extends Model
{
    public string $user_account;
    public string $user_password;
    public bool $rememberMe = true;

    private $_user = false;

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'user_account' => 'User Account',
            'user_passwd' => 'User Passwd',
            'remember_me' => 'Remember Me',
        ];
    }

    public function getAttributes($names = null, $except = [])
    {
        return parent::getAttributes($names, $except); // TODO: Change the autogenerated stub
    }

    /**
     * @return array the validation rules.
     */
    public function rules(): array
    {
        return [
            // user account and password are both required
            [['user_account', 'user_password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['user_password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword(string $attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->user_password)) {
                $this->addError($attribute, 'Incorrect user account or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login(): bool
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return SysUser|null
     */
    public function getUser(): ?SysUser
    {
        if ($this->_user === false) {
            $this->_user = SysUser::findByUserAccount($this->user_account);
        }

        return $this->_user;
    }
}
